package com.ybkj.o2o.mc.controller.res;

import com.alibaba.fastjson.JSON;
import com.ybkj.o2o.mc.controller.v4.ErrorConstantV4;
import com.ybkj.o2o.mc.controller.v4.ResultTransport;
import com.ybkj.o2o.mc.entity.PassengerGradeAndArea;
import com.ybkj.o2o.mc.manager.EnterpriseManager;
import com.ybkj.o2o.mc.manager.PassengerGradeAndAreaManager;
import com.google.common.base.Preconditions;

import com.ybkj.o2o.mc.common.query.PassengerQuery;
import com.ybkj.o2o.mc.common.transport.Error;
import com.ybkj.o2o.mc.common.transport.Result;
import com.ybkj.o2o.mc.entity.PassengerGrade;
import com.ybkj.o2o.mc.manager.PassengerGradeManager;
import com.ybkj.o2o.mc.manager.PassengerManager;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by shine on 15/8/25.
 */
@RestController
@RequestMapping("api/grades")
public class PassengerGradeRes {

  @Autowired
  private PassengerGradeManager passengerGradeManager;

  @Autowired
  private PassengerManager passengerManager;

  @Autowired
  private PassengerGradeAndAreaManager passengerGradeAndAreaManager;

  @Autowired
  private EnterpriseManager enterpriseManager;

  /**
   * 等级创建.
   */
  @RequestMapping(value = {"", "/"}, method = RequestMethod.POST)
  public ResponseEntity<Object> create(
          @RequestParam("name") String name,
          @RequestParam("appKey") String appKey,
          @RequestParam(required = false, value = "limitAmounts") Integer limitAmounts,
          @RequestParam(required = false, value = "dailyOrders") Integer dailyOrders,
          @RequestParam(required = false, value = "defaultGrade") Boolean defaultGrade,
          @RequestParam(required = false, value = "companyId") Long companyId,
          @RequestParam(required = false, value = "companyName") String companyName,
          @RequestParam(required = false, value = "daijiaAreaId") Long daijiaAreaId,
          @RequestParam(required = false, value = "tzAreaId") Long tzAreaId,
          @RequestParam(required = false, value = "brzAreaId") Long brzAreaId,
          @RequestParam(required = false, value = "rzAreaId") Long rzAreaId,
          @RequestParam(required = false, value = "jjAreaId") Long jjAreaId,
          @RequestParam(required = false, value = "sjAreaId") Long sjAreaId,
          @RequestParam(required = false, value = "jzAreaId") Long jzAreaId,
          @RequestParam(required = false, value = "szAreaId") Long szAreaId,
          @RequestParam(required = false, value = "parallelOrderNumber") Long parallelOrderNumber,
          @RequestParam(required = false, value = "carTypes") String carTypes) {

    ResponseEntity<Object> responseEntity = null;

    name = StringUtils.trimToEmpty(name);
    appKey = StringUtils.trimToEmpty(appKey);

    Preconditions.checkArgument(StringUtils.isNotBlank(name), "等级名称不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

    // 判断是否存在相同
    Long getgrade = passengerGradeManager.countByNameAndAppKey(name, companyId, appKey);



    if (getgrade > 0) {

      Result<PassengerGrade> result = new Result<PassengerGrade>(-1, "等级名称已经存在", null);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
      
    }

    //保存
    try {
      PassengerGrade passengerGrade = new PassengerGrade();
      passengerGrade.setName(name);
      passengerGrade.setCompanyId(companyId);
      passengerGrade.setCompanyName(companyName);
      if (null != defaultGrade && defaultGrade) {
        PassengerGrade grade = passengerGradeManager.findDefaultByCompanyId(companyId,appKey);
        if (null != grade) {
          passengerGradeManager.updateDefaultGrade(
              false,grade.getId(),grade.getCompanyId(), appKey);
        }
        passengerGrade.setDefaultGrade(defaultGrade);
      } else {
        passengerGrade.setDefaultGrade(false);
      }
      passengerGrade.setAppKey(appKey);

      passengerGrade.setLimitAmounts(limitAmounts);
      passengerGrade.setDailyOrders(dailyOrders);
      passengerGrade.setDaijiaAreaId(daijiaAreaId);
      passengerGrade.setTzAreaId(tzAreaId);
      passengerGrade.setBrzAreaId(brzAreaId);
      passengerGrade.setRzAreaId(rzAreaId);
      passengerGrade.setJjAreaId(jjAreaId);
      passengerGrade.setSjAreaId(sjAreaId);
      passengerGrade.setJzAreaId(jzAreaId);
      passengerGrade.setSzAreaId(szAreaId);
      if (parallelOrderNumber != null) {
        passengerGrade.setParallelOrderNumber(parallelOrderNumber);
      }

      PassengerGrade pg = passengerGradeManager.insert(passengerGrade);

      List<PassengerGradeAndArea> passengerGradeAndArea = JSON.parseArray(carTypes, PassengerGradeAndArea.class);
      if (passengerGradeAndArea != null) {
        for (PassengerGradeAndArea pa : passengerGradeAndArea) {
          pa.setGradeId(pg.getId());
          pa.setAppKey(pg.getAppKey());
          passengerGradeAndAreaManager.insert(pa);
        }
      }

      Result<PassengerGrade> result = new Result<>(0, "成功", pg);

      responseEntity = new ResponseEntity<>(result, HttpStatus.CREATED);



      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }

  }

  /**
   * 等级修改.
   */
  @RequestMapping(value = "{gradeId}", method = RequestMethod.PUT)
  public ResponseEntity<Object> update(
          @PathVariable("gradeId") Long gradeId,
          @RequestParam("name") String name,
          @RequestParam("appKey") String appKey,
          @RequestParam(required = false, value = "companyId") Long companyId, 
          @RequestParam(required = false, value = "defaultGrade") Boolean defaultGrade, 
          @RequestParam(required = false, value = "limitAmounts") Integer limitAmounts,
          @RequestParam(required = false, value = "dailyOrders") Integer dailyOrders,
          @RequestParam(required = false, value = "daijiaAreaId") Long daijiaAreaId,
          @RequestParam(required = false, value = "tzAreaId") Long tzAreaId,
          @RequestParam(required = false, value = "brzAreaId") Long brzAreaId,
          @RequestParam(required = false, value = "rzAreaId") Long rzAreaId,
          @RequestParam(required = false, value = "jjAreaId") Long jjAreaId,
          @RequestParam(required = false, value = "sjAreaId") Long sjAreaId,
          @RequestParam(required = false, value = "jzAreaId") Long jzAreaId,
          @RequestParam(required = false, value = "szAreaId") Long szAreaId,
          @RequestParam(required = false, value = "parallelOrderNumber") Long parallelOrderNumber,
          @RequestParam(required = false, value = "carTypes")String carTypes) {
    ResponseEntity<Object> responseEntity = null;

    name = StringUtils.trimToEmpty(name);
    appKey = StringUtils.trimToEmpty(appKey);

    Preconditions.checkArgument(gradeId != null && gradeId != 0, "等级Id不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(name), "等级名称不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

    //判断是否存在該等級
    PassengerGrade passengerGrade = passengerGradeManager.fetch(gradeId, null, appKey);

    Preconditions.checkArgument(passengerGrade != null, "等级不存在");
      
    PassengerGrade grade = passengerGradeManager.findByNameAndCompanyId(name, 
        passengerGrade.getCompanyId(),appKey);
    
    if (null != grade && !passengerGrade.getId().equals(grade.getId())) {

      Result<PassengerGrade> result = new Result<PassengerGrade>(-1, "等级名称已经存在", null);

      responseEntity = new ResponseEntity<Object>(result, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }
    
    //修改
    try {

      passengerGrade.setName(name);
      
      if (null != defaultGrade && defaultGrade) {
        PassengerGrade defaultgrade = passengerGradeManager.findDefaultByCompanyId(
            passengerGrade.getCompanyId(),appKey);
        if (null != defaultgrade && !defaultgrade.getId().equals(passengerGrade.getId())) {
          passengerGradeManager.updateDefaultGrade(false,defaultgrade.getId(),
              defaultgrade.getCompanyId(), appKey);
        }
      }
      if (null != defaultGrade) {
        passengerGrade.setDefaultGrade(defaultGrade);
      }
      if (null != limitAmounts) {
        passengerGrade.setLimitAmounts(limitAmounts);
      }
      if (null != dailyOrders) {
          passengerGrade.setDailyOrders(dailyOrders);
      }
      passengerGrade.setAppKey(appKey);
      passengerGrade.setVersion(passengerGrade.getVersion()); //记录版本
      passengerGrade.setDaijiaAreaId(daijiaAreaId);
      passengerGrade.setTzAreaId(tzAreaId);
      passengerGrade.setBrzAreaId(brzAreaId);
      passengerGrade.setRzAreaId(rzAreaId);
      passengerGrade.setJjAreaId(jjAreaId);
      passengerGrade.setSjAreaId(sjAreaId);
      passengerGrade.setJzAreaId(jzAreaId);
      passengerGrade.setSzAreaId(szAreaId);
      if (parallelOrderNumber != null) {
        passengerGrade.setParallelOrderNumber(parallelOrderNumber);
      }

      passengerGradeManager.updateByPrimaryKey(passengerGrade);

      List<PassengerGradeAndArea> passengerGradeAndArea = JSON.parseArray(carTypes, PassengerGradeAndArea.class);

      passengerGradeAndAreaManager.delete(passengerGrade.getId(),passengerGrade.getAppKey());

      if (passengerGradeAndArea != null) {
        for (PassengerGradeAndArea pa : passengerGradeAndArea) {
          pa.setGradeId(passengerGrade.getId());
          pa.setAppKey(passengerGrade.getAppKey());
          passengerGradeAndAreaManager.insert(pa);
        }
      }

      Result<PassengerGrade> result = new Result<>(0, "成功", null);

      responseEntity = new ResponseEntity<>(result, HttpStatus.CREATED);

      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }

  }


  /**
   * 刪除等級.
   */
  @RequestMapping(value = "deleteGrade/{gradeId}", method = RequestMethod.DELETE)
  public ResponseEntity<Object> delete(
      @PathVariable("gradeId") Long gradeId, 
      @RequestParam(required = false, value = "companyId") Long companyId, 
      @RequestParam("appKey") String appKey) {

    ResponseEntity<Object> responseEntity = null;

    appKey = StringUtils.trimToEmpty(appKey);

    Preconditions.checkArgument(gradeId != null && gradeId != 0, "等级Id不能为空");
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    
    //判断是否存在該等級
    PassengerGrade grade = passengerGradeManager.fetch(gradeId, null, appKey);
    Preconditions.checkArgument(grade != null, "等级不存在");

    PassengerQuery passengerQuery = new PassengerQuery();
    passengerQuery.setGradeId(gradeId);
    passengerQuery.setAppKey(appKey);

//    long total = passengerManager.countByPassengerQuery(passengerQuery);
//    Preconditions.checkArgument(total == 0, "此等级不能刪除,请先修改客户等级为其他等级");

    //删除
    try {

      passengerGradeManager.deleteGrade(gradeId, appKey);

      Result<PassengerGrade> result = new Result<>(0, "成功", null);

      responseEntity = new ResponseEntity<>(result, HttpStatus.NO_CONTENT);

      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace()  ;
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());
      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
      return responseEntity;
    }

  }

  /**
   * 根据appKey查询所有等级.
   */
  @RequestMapping(value = {"", "/"}, method = RequestMethod.GET)
  public ResponseEntity<Object> findByType(@RequestParam("appKey") String appKey) {

    ResponseEntity<Object> responseEntity = null;

    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");
    try {
      List<PassengerGrade> list = passengerGradeManager.findByAppKey(appKey);
      Result<List<PassengerGrade>> result = new Result<>(0, "成功", list);
      responseEntity = new ResponseEntity<>(result, HttpStatus.OK);
      return responseEntity;
    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }
  }

  /**
   * 根据ID查询单个等级 .
   */
  @RequestMapping(value = "{gradeId}", method = RequestMethod.GET)
  public ResponseEntity<Object> getPassengerGrade(
      @PathVariable("gradeId") Long gradeId,
      @RequestParam(required = false, value = "companyId") Long companyId,
      @RequestParam("appKey") String appKey) {

    ResponseEntity<Object> responseEntity = null;

    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

    PassengerGrade passengerGrade = passengerGradeManager.fetch(gradeId, null, appKey);
    Preconditions.checkArgument(passengerGrade != null, "等级不存在");

    try {

      Result<PassengerGrade> result = new Result<>(0, "成功", passengerGrade);

      responseEntity = new ResponseEntity<>(result, HttpStatus.OK);

      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }
  }

  /**
   * 根据公司id查询客户等级 .
   * @param companyId 公司id
   * @param appKey  appKey
   */
  @RequestMapping(value = "findByCompanyId", method = RequestMethod.GET)
  public ResponseEntity<Object> findBycompanyId(
      @RequestParam("companyId") Long companyId,
      @RequestParam("appKey") String appKey) {

    ResponseEntity<Object> responseEntity = null;

    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

    List<PassengerGrade> passengerGrade = passengerGradeManager.findByCompany(companyId,appKey);

    try {

      Result<List<PassengerGrade>> result = new Result<>(0, "成功", passengerGrade);

      responseEntity = new ResponseEntity<>(result, HttpStatus.OK);

      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }
  }

  /**
   * 处理等级 .
   * @param gradeId 等级id
   * @param appKey  appKey
   */
  @RequestMapping(value = "disposeGrade/{gradeId}", method = RequestMethod.POST)
  public ResponseEntity<Object> disposeGrade(
          @PathVariable("gradeId") Long gradeId,
          @RequestParam("appKey") String appKey) {

    ResponseEntity<Object> responseEntity = null;

    appKey = StringUtils.trimToEmpty(appKey);
    Preconditions.checkArgument(StringUtils.isNotBlank(appKey), "AppKey不能为空");

    PassengerGrade pg = passengerGradeManager.findByIdAndAppKey(gradeId,appKey);
    Preconditions.checkArgument(pg != null, "等级不存在");
    if (pg.getCompanyId() != null) {
      passengerManager.disposeGrade(gradeId,pg.getName(),pg.getCompanyId(),appKey);
      enterpriseManager.disposeGrade(gradeId,pg.getName(),pg.getCompanyId(),appKey);
    }else {
      ResultTransport.getErrorBy(ErrorConstantV4.PASSENGERGRADE_COMPANY_ISNULL);
    }
    try {

      Result<PassengerGrade> result = new Result<>(0, "成功", pg);

      responseEntity = new ResponseEntity<>(result, HttpStatus.OK);

      return responseEntity;

    } catch (Exception ex) {
      ex.printStackTrace();
      Error error = new Error(500, "内部服务器错误：" + ex.getMessage());

      responseEntity = new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);

      return responseEntity;
    }
  }
}
